﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESF.General.MVP;
using ESF.SFT.FileUploader.Presenter.FileReceiverGeneral;
using ESF.SFT.FileUploader.Presenter.FileReceiver;
using ESF.General;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.IO;

#endregion


namespace ESF.SFT.FileUploader.Presenter.FileSelection
{
	public class FileUploaderWindowPresenter : BasePresenter<IFileUploaderWindowViewer>
	{
		#region Miembros

		public ReceiverGeneralClient _ReceiverGeneralClient;
		public ReceiverClient _ReceiverClient;

		#endregion
		
		
		#region Constructor

		public FileUploaderWindowPresenter(IFileUploaderWindowViewer pViewer)
			: base (pViewer) 
		{
			
		}

		#endregion


		#region Funciones

		public override void Load()
		{
			try
			{
				_ReceiverGeneralClient = new ReceiverGeneralClient();
				_ReceiverClient = new ReceiverClient ();
				_ReceiverClient.UploadFileCompleted += _ReceiverClient_UploadFileCompleted;
			}
			catch (Exception pEx)
			{
				LogError(pEx);
				return;
			}

			_Viewer.ProductVersion = string.Format ("Versión: {0}", ReadConfig.ExecutingVersion);
			_Viewer.Title = ReadConfig.ApplicationName;
		}


		private void _ReceiverClient_UploadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			_Viewer.RemoveUploadedFromList (e.UserState as string []);
		}


		private static X509Certificate2 SearchCertificateStoreWindows (StoreName storeName, string pMessage)
        {
            //Definir el almacén en el que se va a buscar
            X509Store store = new X509Store (StoreLocation.CurrentUser);
            
			store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
            X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
            X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Seleccione un Certificado", pMessage, X509SelectionFlag.SingleSelection);

            //Buscar el certificado en el almacén
            if (scollection.Count > 0)
			{
				return scollection [0];
			}
			else
			{
				return null;
			}
        }

		#endregion
	}
}
